<template>
  <div class="table-container">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="table-wrapper">
        <div class="table-scroll">
          <!-- 左侧固定列 -->
          <div class="fixed-left" v-if="leftFixedColumns.length">
            <div class="table-header">
              <div
                v-for="column in leftFixedColumns"
                :key="column.prop"
                class="table-cell"
                :style="{ width: column.width || 'auto' }"
              >
                {{ column.title }}
              </div>
            </div>
            <div class="table-body">
              <div
                v-for="(row, rowIndex) in tableData"
                :key="rowIndex"
                class="table-row"
                :style="{ height: rowHeights[rowIndex] + 'px' }"
              >
                <div
                  v-for="column in leftFixedColumns"
                  :key="column.prop"
                  class="table-cell"
                  :style="{ width: column.width || 'auto' }"
                >
                  <slot
                    v-if="column.slot"
                    :name="column.slot"
                    :row="row"
                    :column="column"
                    :index="rowIndex"
                  />
                  <template v-else>
                    <template v-if="isEmptyRow(row)">
                      <van-field
                        v-model="row[column.prop]"
                        :placeholder="`请输入${column.title}`"
                        @click.stop
                        @change="(value) => handleFieldChange(value, row, column.prop)"
                      />
                    </template>
                    <template v-else>
                      {{ row[column.prop] }}
                    </template>
                  </template>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧固定列 -->
          <div class="fixed-right" v-if="rightFixedColumns.length">
            <!-- 固定表头 -->
            <div class="table-header">
              <div
                v-for="column in rightFixedColumns"
                :key="column.prop"
                class="table-cell"
                :style="{ width: column.width || 'auto', minWidth: column.minWidth || '100px' }"
              >
                {{ column.title }}
              </div>
            </div>
            <!-- 固定内容 -->
            <div class="table-body">
              <div
                v-for="(row, rowIndex) in tableData"
                :key="rowIndex"
                class="table-row"
                :style="{ height: rowHeights[rowIndex] + 'px' }"
              >
                <div
                  v-for="column in rightFixedColumns"
                  :key="column.prop"
                  class="table-cell"
                  :style="{ width: column.width || 'auto', minWidth: column.minWidth || '100px' }"
                >
                  <slot
                    v-if="column.slot"
                    :name="column.slot"
                    :row="row"
                    :column="column"
                    :index="rowIndex"
                  >
                  </slot>
                  <template v-else>
                    <template v-if="isEmptyRow(row)">
                      <van-field
                        v-model="row[column.prop]"
                        :placeholder="`请输入${column.title}`"
                        @click.stop
                        @change="(value) => handleFieldChange(value, row, column.prop)"
                      />
                    </template>
                    <template v-else>
                      {{ row[column.prop] }}
                    </template>
                  </template>
                </div>
              </div>
            </div>
          </div>

          <!-- 主体内容 -->
          <div 
            class="table-main"
            :style="{
              marginLeft: leftFixedWidth + 'px',
              marginRight: rightFixedWidth + 'px'
            }"
          >
            <!-- 可滚动列 -->
            <div 
              class="scroll-columns"

            >
              <div class="table-header">
                <div
                  v-for="column in scrollColumns"
                  :key="column.prop"
                  class="table-cell"
                  :style="{ width: column.width || 'auto' }"
                >
                  {{ column.title }}
                </div>
              </div>
              <div class="table-body">
                <div
                  v-for="(row, rowIndex) in tableData"
                  :key="rowIndex"
                  class="table-row"
                  @click="handleRowClick(row, rowIndex)"
                  ref="rowRefs"
                >
                  <div
                    v-for="column in scrollColumns"
                    :key="column.prop"
                    class="table-cell"
                    :style="{ width: column.width || 'auto' }"
                  >
                    <slot
                      v-if="column.slot"
                      :name="column.slot"
                      :row="row"
                      :column="column"
                      :index="rowIndex"
                    />
                    <template v-else>
                      <template v-if="isEmptyRow(row)">
                        <van-field
                          v-model="row[column.prop]"
                          :placeholder="`请输入${column.title}`"
                          @click.stop
                          @change="(value) => handleFieldChange(value, row, column.prop)"
                        />
                      </template>
                      <template v-else>
                        {{ row[column.prop] }}
                      </template>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { showToast } from 'vant'

const props = defineProps({
  columns: {
    type: Array,
    required: true
  },
  data: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['row-click', 'refresh', 'field-change'])

// 表格数据
const tableData = ref([])
const rowRefs = ref([])
const rowHeights = ref([])

// 计算固定列和可滚动列
const leftFixedColumns = computed(() => props.columns.filter(col => col.fixed === 'left'))
const rightFixedColumns = computed(() => props.columns.filter(col => col.fixed === 'right'))
const scrollColumns = computed(() => props.columns.filter(col => !col.fixed))

// 计算左侧固定列宽度
const leftFixedWidth = computed(() => {
  return leftFixedColumns.value.reduce((total, col) => {
    return total + (parseInt(col.width) || 100)
  }, 0)
})

// 计算右侧固定列宽度
const rightFixedWidth = computed(() => {
  return rightFixedColumns.value.reduce((total, col) => {
    return total + (parseInt(col.width) || 100)
  }, 0)
})

// 更新行高
const updateRowHeights = () => {
  nextTick(() => {
    if (rowRefs.value) {
      rowHeights.value = rowRefs.value.map(row => row?.offsetHeight || 0)
    }
  })
}

// 监听数据变化
watch(() => props.data, (newVal) => {
  tableData.value = newVal
  updateRowHeights()
}, { immediate: true })

// 刷新状态
const refreshing = ref(false)

// 处理下拉刷新
const onRefresh = async () => {
  try {
    emit('refresh')
    await new Promise(resolve => setTimeout(resolve, 1000))
    showToast('刷新成功')
  } finally {
    refreshing.value = false
  }
}

// 行点击事件
const handleRowClick = (row, index) => {
  emit('row-click', row, index)
}

// 判断是否为空行
const isEmptyRow = (row) => {
  return !row.name && !row.employeeId && !row.department
}

const handleFieldChange = (value, row, prop) => {
  emit('field-change', { value, row, prop })
}

onMounted(() => {
  updateRowHeights()
  window.addEventListener('resize', updateRowHeights)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateRowHeights)
})
</script>

<style scoped>
.table-container {
  width: 100%;
  position: relative;
}

.table-wrapper {
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.table-scroll {
  width: 100%;
  overflow-x: auto;
  position: relative;
}

/* 固定列样式 */
.fixed-left {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 2;
  background: #fff;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}

.fixed-right {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 2;
  background: #fff;
  box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1);
}

.table-main {
  overflow-x: auto;
}

/* 滚动阴影效果 */
.table-scroll {
  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    width: 30px;
    pointer-events: none;
    transition: box-shadow .3s;
    z-index: 1;
  }

  &::before {
    left: 0;
    box-shadow: inset 10px 0 8px -8px rgba(0, 0, 0, 0.15);
  }

  &::after {
    right: 0;
    box-shadow: inset -10px 0 8px -8px rgba(0, 0, 0, 0.15);
  }
}

.table-header {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.table-body {
  background-color: #ffffff;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:hover {
    background-color: #f5f7fa;
  }
}

.table-cell {
  flex-shrink: 0;
  padding: 12px 8px;
  display: flex;
  align-items: center;
  overflow: hidden;
  min-height: 48px;
  box-sizing: border-box;
  white-space: nowrap;
}

/* 添加输入框样式 */
:deep(.van-field) {
  padding: 0;
  background: transparent;
}

:deep(.van-field__control) {
  height: 24px;
  padding: 0;
  border: none;
  font-size: 14px;
}

/* 空行样式 */
.table-row:has(.van-field) {
  background-color: #fafafa;
}

/* 自定义滚动条样式 */
.table-scroll::-webkit-scrollbar {
  height: 6px;
}

.table-scroll::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.table-scroll::-webkit-scrollbar-track {
  background: #f5f7fa;
}
</style>

